package com.example.demo.controller;

import com.example.demo.dto.StudentDTO;
import com.example.demo.service.DemoDService;
import com.example.demo.mvc.WithApiResult;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

//@WithApiResult
@RestController
public class DemoController implements ApplicationContextAware, ApplicationContextInitializer {

    private ApplicationContext applicationContext;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private DemoDService demoDService;

    @GetMapping("/test")
    public void test() {
        Cookie cookie = new Cookie("test", "1223456");
        HttpSession session = request.getSession();
        if (session != null) {
            System.out.println(session.getId());
        }

        response.addCookie(cookie);
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            cookie.getName();
//        }
        request.setAttribute("111", "aaa");

        demoDService.test();

        // ((ConfigurableApplicationContext)applicationContext).refresh();

        // return "demo";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        // this.applicationContext = applicationContext;
    }

    @WithApiResult
    @GetMapping("/student/info")
    public StudentDTO getStudent(String check, @Valid StudentDTO studentDTO) {
        if (check != null && check.length() > 0) {
            throw new RuntimeException("Invaild input");
        }
        StudentDTO student = StudentDTO.builder().build();
        student.setAge(34);
        student.setClassNo("3年一班");
        student.setName("张三");

        System.out.println(JSON.toJSONString(studentDTO));
        return student;
    }
}
